package com.changgou.canal;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.changgou.config.RabbitMqConfig;
import com.changgou.util.CanalUtil;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.UpdateListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * @author 戴金华
 * @date 2019-12-20 19:05
 */
@CanalEventListener
public class GoodsListener {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 监控spu表的数据更新变化
     * @param eventType
     * @param rowData
     */
    @UpdateListenPoint(schema = "changgou_goods",table = "tb_spu")
    public void update(CanalEntry.EventType eventType, CanalEntry.RowData rowData){
        //获取更新之前的数据
        Map<String, String> beforeMap = CanalUtil.convertToMap(rowData.getBeforeColumnsList());
        String beforeMarketable = beforeMap.get("is_marketable");

        //获取更新之后的数据变化
        Map<String, String> afterMap = CanalUtil.convertToMap(rowData.getAfterColumnsList());
        String afterMarketable = afterMap.get("is_marketable");
        //如果更新前未上架且更新后上架 则将消息发给search_add_queue
        if ("0".equals(beforeMarketable)&&"1".equals(afterMarketable)){
            rabbitTemplate.convertAndSend(RabbitMqConfig.GOODS_UP_EXCHANGE,"",afterMap.get("id"));
        }
        //如果更新前上架且更新后未上架 则将消息发给search_delete_queue
        if ("1".equals(beforeMarketable)&&"0".equals(afterMarketable)){
            rabbitTemplate.convertAndSend(RabbitMqConfig.GOODS_DOWN_EXCHANGE,"",afterMap.get("id"));
        }
        //如果审核通过 则将消息发送给队列 通知生成静态页面
        if ("0".equals(beforeMap.get("status"))&&"1".equals(afterMap.get("status"))){
            rabbitTemplate.convertAndSend(RabbitMqConfig.GOODS_UP_EXCHANGE,"",afterMap.get("idc"));
        }
    }

}
